<template>
    <div style="background-color: white; margin-top: 20px">

        <a-button v-show="false" style="margin: 10px" type="primary"
                  @click="()=> {visible = true;addLayerOneFrom.resetFields()}">
            添加一级区域
        </a-button>

        <a-modal
            :title="needUpdateArea === null ? '添加区域':'编辑区域'"
            :visible="visible"
            @cancel="visible=false"
            @ok="handleOk"
        >

            <a-form :form="addLayerOneFrom" :label-col="{ span: 4, offset: 0}" :wrapper-col="{ span: 24 }">
                <a-form-item label="区域编号">
                    <a-input
                        v-decorator="['key', { rules: [{ required: true, message: '请输入区域编号!' },{ validator: checkKey }] }]"/>
                </a-form-item>
                <a-form-item label="区域名称">
                    <a-input
                        v-decorator="['title', { rules: [{ required: true, message: '请输入区域名称!' }] }]"/>
                </a-form-item>
            </a-form>

        </a-modal>


        <a-table
            v-if="data.length"
            :columns="columns"
            :data-source="data"
            :pagination="false"
            defaultExpandAllRows
            rowKey="id"
        >
            <!--            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"-->

            <span slot="dateSlot" slot-scope="date">
                {{
                    moment(date * 1000).format("YYYY-MM-DD HH:mm:ss")
                }}
            </span>
            <span slot="ifShowSlot" slot-scope="item">
                <a-switch :key="item.id" :checked="item.mark" checked-children="开" un-checked-children="关"
                          @change="onChange($event, item)"/>
            </span>

            <div slot="actionSlot" slot-scope="item">
                <ul class="action-list" style="list-style: none;">
                    <li v-show="item.level === 2">
                        <a-button size="small" type="primary" @click="addArea(item);">添加区域</a-button>
                    </li>
                    <li v-show="item.level > 1">
                        <a-button size="small" type="primary" @click="updateAreaBtn(item)">编辑区域</a-button>
                    </li>
                    <li v-show="item.level === 3">
                        <a-button size="small" type="plain" @click="showConfirm(item, userID)">删除</a-button>
                    </li>
                </ul>
            </div>
        </a-table>

        <div v-show="false" style="margin-left: 16px">


            <a-button :disabled="!hasSelected" :loading="loading" type="primary" @click="batchDelete">
                批量删除
            </a-button>

            <span style="margin-left: 8px">
        <template v-if="hasSelected">
          {{ `共 ${selectedRowKeys.length} 条` }}
        </template>
      </span>
        </div>

    </div>
</template>

<script>
import {METHOD, request} from "@/utils/request";
import moment from "moment";

const columns = [
    {},
    {
        title: '区域编号',
        key: 'key',
        dataIndex: 'key',
    },
    {
        title: '区域名称',
        key: 'title',
        dataIndex: 'title',
    },
    {
        title: '层级',
        key: 'level',
        dataIndex: 'level',
    },
    {
        title: '添加时间',
        key: 'date',
        dataIndex: 'date',
        scopedSlots: {customRender: 'dateSlot'},
    },
    {
        title: '是否显示',
        key: 'mark',
        scopedSlots: {customRender: 'ifShowSlot'},
    },
    {
        title: '操作',
        key: 'action',
        scopedSlots: {customRender: 'actionSlot'},
    },
];


export default {
    name: 'Success',
    // components: {AStepItemGroup, AStepItem, DetailListItem, DetailList, Result},
    data() {
        return {
            moment,
            needUpdateArea: null,
            level: 1,
            userID: null,
            parentAreaId: 0,
            addLayerOneFrom: this.$form.createForm(this, {name: 'coordinated'}),
            visible: false,
            batchDeleteVisible: true,
            data: [],
            columns,
            selectedRowKeys: [], // Check here to configure the default column
            loading: false,
        }
    },
    computed: {
        hasSelected() {
            return this.selectedRowKeys.length > 0;
        },
    },
    mounted() {
        this.userID = JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_KEY)).id;

        console.log("mounted" + this.userID);
        this.refreshList();
    },
    methods: {
        checkKey(rule, value, callback) {
            const n = Number(value);
            console.log(value);
            if (!isNaN(n) || value === undefined) {
                // 是数字或者没有输入，不用提示
                callback();
            } else {
                callback("区域编号只能输入数字")
            }
        },
        onChange(e, item) {
            console.log(item);

            // complete data
            item.mark = !item.mark;

            this.$set(item, "user_id", this.userID)

            // request data
            request("/areas/updateAreasByid", METHOD.PUT, item).then(result => {

                if (result.data.code === 1) {
                    this.refreshList();
                } else {
                    this.$message.error(result.data.msg);
                }
            })
        },
        updateArea(item) {
            request("/areas/updateAreas", METHOD.PUT, item).then(result => {

                if (result.data.code === 1) {
                    this.refreshList();
                } else {
                    this.$message.error(result.data.msg);
                }
            })
        },
        refreshList() {
            request("/areas/getAreas?id=" + this.userID, METHOD.GET).then(result => {
                if (result.data.code === 1) {
                    this.data = result.data.data;
                    this.$message.success('成功');
                }
            })
        },
        // 添加一级区域
        handleOk() {
            this.addLayerOneFrom.validateFields((err, values) => {
                if (!err) {

                    if (this.needUpdateArea !== null) {
                        this.needUpdateArea.key = values.key;
                        this.needUpdateArea.title = values.title;
                        this.needUpdateArea.user_id = this.userID;
                        this.updateArea(this.needUpdateArea);
                    } else {
                        this.$set(values, "user_id", this.userID)
                        this.$set(values, "level", this.level)
                        this.$set(values, "mark", true)
                        this.$set(values, "parentld", this.parentAreaId)
                        this.$set(values, "date", moment().valueOf() / 1000)


                        // 添加一个新的区域的请求
                        request("/areas/saveAreas", METHOD.POST, values).then(result => {
                            if (result.data.code === 1) {
                                // 刷新列表
                                this.refreshList();
                            } else {
                                // 弹出错误提升
                                this.$message.error(result.data.msg)
                            }
                        })
                    }

                    // 隐藏添加弹窗
                    this.visible = false
                }
            });
        },
        batchDelete() {
            const that = this;

            this.$confirm({
                title: '删除后将不能恢复，确认删除吗?',
                onOk() {
                    for (let i = 0; i < that.selectedRowKeys.length; i++) {
                        request("/areas/deleteAreasByid?id=" + that.selectedRowKeys[i], METHOD.DELETE).then(() => {
                            if (i + 1 === that.selectedRowKeys.length) {
                                that.refreshList();
                            }
                        })
                    }
                },
                onCancel() {

                }
            });
        },
        showConfirm(item, userID) {

            console.log(this.selectedRowKeys);
            const that = this;

            this.$confirm({
                title: '删除后将不能恢复，确认删除吗?',
                onOk() {
                    request("/areas/deleteAreasByid?id=" + item.id, METHOD.DELETE).then(result => {
                        console.log(result.data);
                        if (result.data.code === 1) {
                            // 刷新列表
                            request("/areas/getAreas?id=" + userID, METHOD.GET).then(result => {
                                that.data = result.data.data;
                            })
                        } else {
                            this.$message.error(result.data.msg)
                        }
                    })
                },
                onCancel() {
                    console.log('Cancel');
                },
                class: 'test',
            });
        },
        onSelectChange(selectedRowKeys) {
            console.log('selectedRowKeys changed: ', selectedRowKeys);
            this.selectedRowKeys = selectedRowKeys;
        },
        addArea(item) {
            this.needUpdateArea = null;

            // 清空所有字段值
            this.addLayerOneFrom.resetFields();

            // 将要添加的节点层级 = 母亲节点的层级 + 1
            this.level = item.level + 1;
            // 当前节点为将要添加的节点的父节点
            this.parentAreaId = item.key
            // 弹出添加界面
            this.visible = true;
        },
        updateAreaBtn(item) {
            // 记录需要编辑的区域
            this.needUpdateArea = item;

            // 将编辑前的值也到控件
            this.addLayerOneFrom.setFieldsValue(item)

            // 弹出添加界面
            this.visible = true;
        }
    },
}
</script>

<style lang="less" scoped>
.result-success {
    .action:not(:first-child) {
        margin-left: 8px;
    }

    .project-name {
        font-size: 16px;
        color: @title-color;
        font-weight: 500;
        margin-bottom: 20px;
    }
}

.action-list li {
    display: inline;
    margin-left: 6px;
}
</style>
